package com.itheima.service.empl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Category;
import com.itheima.bean.Dish;
import com.itheima.bean.Setmeal;
import com.itheima.dao.CategoryDao;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {


    @Autowired
    private CategoryDao categoryDao;

    @Lazy
    @Autowired
    private DishServiceImpl dishService;

    @Autowired
    private SetmealServiceImpl setmealService;

    /**
     * 添加菜品和套餐分类
     *
     * @param category
     * @return
     */
    @Override
    public int add(Category category) {
        return categoryDao.insert(category);
    }

    /**
     * 分页查询菜品和套餐分类
     *
     * @return
     */
    @Override
    public IPage<Category> findPage(int page, int pageSize) {

        IPage<Category> pag = new Page<>(page, pageSize);

        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();

        qw.orderByDesc(Category::getType);

        qw.orderByAsc(Category::getSort);


        return categoryDao.selectPage(pag, qw);
    }

    /**
     * 修改菜品和套餐分类
     *
     * @param category
     * @return
     */
    @Override
    public int update(Category category) {
        return categoryDao.updateById(category);
    }

    /**
     * 删除菜品和套餐分类
     *
     * @param id
     * @return
     */
    @Override
    public int delete(Long id, Integer type) {


        if (type == 1) {

            List<Dish> dishList = dishService.findCond(id);

            if (dishList != null && dishList.size() > 0) {

                return -1;

            }
        } else {
            List<Setmeal> setmealList = setmealService.findCond(id);

            if (setmealList != null && setmealList.size() > 0) {

                return -2;
            }
        }


        return categoryDao.deleteById(id);
    }

    /**
     * 查找type类型的菜品
     *
     * @param type
     * @return
     */
    @Override
    public List<Category> findType(Integer type) {

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(type != null, Category::getType, type);
        return categoryDao.selectList(lqw);
    }

    /**
     * 通过id查找
     *
     * @param id
     * @return
     */
    @Override
    public Category findById(Long id) {
        return categoryDao.selectById(id);
    }
}
